<script setup>
import MwTable from "./component/MwTableVehicle";
import SearchTable from "./component/SearchVehicle.vue";
import MwDialog from "@/components/Dialog";
import moment from 'moment';
import { ElMessage, ElMessageBox } from 'element-plus';
import FlvVideo from "@/components/flvVideo";

import { VideoPlay, CloseBold } from '@element-plus/icons-vue';
import { ref, reactive, getCurrentInstance, onMounted, watch, nextTick } from "vue";

const instance = getCurrentInstance();
const _this = instance.appContext.config.globalProperties; //vue3获取当前this
const storage = _this.$utils.storage;

import { globalStore } from "@/store/global";
const globalVue = globalStore();

// 生命周期
onMounted(() => {
  getTableData();
  getSelect();
});

let getTableData = () => {
  // 查询救护车
  let paramsVehicle = {
    ...pagination,
    ...searchForm
  };
  searchForm['city'] && (paramsVehicle['city'] = searchForm['city'] + '');
  tablLoading.value = true;
  instance.proxy.$http.get('overview.getAmbulanceList', { params: paramsVehicle }).then(res => {
    let { content, totalElements } = res.data;
    tableData.value = content;
    pagination.total = totalElements;
    tablLoading.value = false;
  }).catch(err => tablLoading.value = false)
}

let getSelect = async () => {
  selectClassification.value = await globalVue.getSelect('classificationSelect');
  citySearchSelect.value = await globalVue.getSelect('citySelect');
  selectCamera.value = await globalVue.getSelect('cameraBindSelect');

  instance.proxy.$http.get('archiveData.dictDetail', { params: { name: 'ambulance_model' } }).then(res => {
    selectModel.value = res.data;
  });
  instance.proxy.$http.get('archiveData.dictDetail', { params: { name: 'ambulance_passager_number' } }).then(res => {
    selectPassager.value = res.data;
  });
  instance.proxy.$http.get('archiveData.dictDetail', { params: { name: 'ambulance_maintain_cycle' } }).then(res => {
    selectCycle.value = res.data;
  });
  instance.proxy.$http.get('archiveData.getHospitalSelect').then(res => {
    selectHospital.value = res.data.map(i => {
      i['label'] = i.selectName;
      i['value'] = i.id;
      return i;
    });
  });
  instance.proxy.$http.get('archiveData.getDriverSelect').then(res => {
    selectDriver.value = res.data.map(i => {
      i['label'] = i.selectName;
      i['value'] = i.id;
      return i;
    });
  });
};

// getHospitalSelect getAmbulanceSelect getCameraSelect getDriverSelect getCitySelect 医院 救护车 摄像头 司机 城市 
// 下拉数据
const citySelect = ref([]);   // 城市
const citySearchSelect = ref([]);   // 搜索中城市

const selectHospital = ref([]);   // 医院
const organizationSelect = ref([]);   // 弹框中医院
const selectDriver = ref([]);   // 司机
const selectModel = ref([]);   // Model
const selectCamera = ref([]);   // 摄像头
const selectCameraDialog = ref([]);   // 摄像头
const selectPassager = ref([]);   // Classification
const selectClassification = ref([]);   // Number Of Passengers
const selectCycle = ref([]);   // Maintenance Cycle

// 弹框数据
let dialogShow = ref(false);
let dialogTitle = ref(' Vehicle');
let dialogState = ref('Add'); //  Add Edit Detail 三种状态 根据状态来判断提交方法
let dialogRef = ref(null);
let dialogFrom = reactive({});
let dialogRules = reactive({
  codenumber: [
    { required: true, message: 'Please input Code', trigger: 'blur' },
    { pattern: /^[^\s]+(\s+[^\s]+)*$/, message: 'String cannot contain spaces', trigger: 'blur' },
  ],
  carnumber: [
    { required: true, message: 'Please input Bind Vehicle', trigger: 'blur' },
  ],
  type: [
    { required: true, message: 'Please input Bind Classification', trigger: 'blur' },
  ],
  hospitalIds: [
    { required: true, message: 'Please input Bind Organization', trigger: 'blur' },
  ],
  name: [
    { required: true, message: 'Please input Vehicle Name', trigger: 'blur' },
  ],
  city: [
    { required: true, message: 'Please input City', trigger: 'blur' },
  ],
  
});
let dialogSubmit = async () => {
  let formEl = dialogRef.value;
  dialogFrom['city'] && (dialogFrom['city'] = dialogFrom['city'] + '')
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      let url = dialogState.value == 'Add' ? 'archiveData.insertAmbulance' : 'archiveData.updateAmbulance';
      if (dialogState.value == 'Add') {
        instance.proxy.$http.post(url, dialogFrom).then(res => {
          if (res.success) {
            onSearch();
            dialogClose();
          };
        });
      } else {
        instance.proxy.$http.put(url, dialogFrom).then(res => {
          if (res.success) {
            onSearch();
            dialogClose();
          };
        });
      };
    } else {
      console.err('error submit!', fields)
    };
  });
};
let dialogClose = () => {
  dialogShow.value = false;
  dialogRef.value.resetFields();
  citySelect.value = [];
  organizationSelect.value = [];
  for (let item in dialogFrom) {
    if (dialogFrom[item] instanceof Array) {
      dialogFrom[item] = [];
    } else {
      dialogFrom[item] = '';
    };
  };
};

function openDialog(state) {
  dialogState.value = state;
  dialogShow.value = true;
  organizationSelect.value = [];
  for (let item in dialogFrom) {
    delete dialogFrom[item];
  };
};

// 表格数据
const tableData = ref([]);
const tablLoading = ref(false);
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
});
const searchForm = reactive({})
// 推流弹框
const plugFlow = ref(false);
const plugVideoFlow = ref(false);
const videoUrl1 = ref('');
const videoUrl2 = ref('');
const hlsVideoBefore = ref(null);
const hlsVideoAfter = ref(null);
const videoData = ref([]);

function onSearch() {
  getTableData();
};

function paginationChange(pagination) {
  onSearch();
};

function rtmpToHttp(url, type) {
  if (!url) return '';
  let str;
  switch (type) {
    case 'm3u8':
      str = url.replace('rtmp://', 'http://') + '/hls.m3u8';
      break;
    default:
      break;
  };
  return str.replace(':1935/', ':8099/');
};


function palyVideo(row) {
  instance.proxy.$http.get('overview.getVideo', { params: { ambulanceId: row.id } }).then(res => {
    res.data.map(i => {
      i['lng'] = Number(i['lng']).toFixed(8);
      i['lat'] = Number(i['lat']).toFixed(8);
      return i;
    });
    videoData.value = res.data || [];
    if (res.data.length == 0) {
      ElMessage({
        type: 'warning',
        message: 'No AIBOX cameras!',
      });
      return;
    };
    // rtmpToHttp(res.data[0]?.rtmpurl, 'm3u8');    res.data[0]?.rtmpurl.replace('rtmp', 'http') || null;
    let url, url1;
    if (res.data[0]?.rtmpurl.indexOf('rtmp://') > -1) {
      url = rtmpToHttp(res.data[0]?.rtmpurl, 'm3u8');
    }else{
      url = res.data[0]?.rtmpurl
    }
    if (res.data[1]?.rtmpurl.indexOf('rtmp://') > -1) {
      url1 = rtmpToHttp(res.data[1]?.rtmpurl, 'm3u8');
    }else{
      url1 = res.data[1]?.rtmpurl
    }
    videoUrl1.value = url;
    videoUrl2.value = url1;
    plugFlow.value = true;
    if (row.status != '0') {
      plugVideoFlow.value = true;
    }else{
      plugVideoFlow.value = false;
    }
    nextTick(() => {
      // 开启推流 
      let uuid = _this.$utils.createHash(18);
      let videoFlow = {
        "uuid": uuid,
        "cameraVideoList": videoData.value
      };
      storage.setLocal('videoFlow', videoFlow);
      instance.proxy.$http.post('overview.openVideoStream', videoFlow).then(res => { });
    });
  });

};
function cliseVideo() {
  plugFlow.value = false;
  if (plugVideoFlow.value) {
    hlsVideoBefore.value.disposeVideo();
    hlsVideoAfter.value.disposeVideo();
    // 关闭推流 
    let videoFlow = storage.getLocal('videoFlow');
    storage.removeLocal('videoFlow');
    instance.proxy.$http.post('overview.closeVideoStream', videoFlow).then(res => { });
    plugVideoFlow.value = false;
  }
};
async function onAdd(){
  let oldArr = await globalVue.getSelect('cameraBindSelect', {});
  let arr= []
  oldArr.forEach(i => {
    i.value = i.value + ''
    i.id = i.id + ''
    !i.bind && arr.push(i)
  })
  selectCamera.value = oldArr;
  selectCameraDialog.value = arr;
  openDialog('Add');
}
async function onDetail(row) {
  let oldArr = await globalVue.getSelect('cameraBindSelect', {});
  let arr= []
  oldArr.forEach(i => {
    i.value = i.value + ''
    i.id = i.id + ''
    if (row && row.cameraId?.split(',').some(j => j == i.id)) {
      arr.push(i)
    }else{
      !i.bind && arr.push(i)
    }
  })
  selectCamera.value = oldArr;
  selectCameraDialog.value = arr;
  
  openDialog('Detail');
  for (let i in row) {
    dialogFrom[i] = row[i];
    if (i == 'retirementperiod') {
      dialogFrom['retirementperiod'] = row[i] ? moment(row[i]).format('YYYY-MM-DD') : '';
    };
    if (i == 'hospitalId') {
      dialogFrom['hospitalIds'] = row[i] || '';
    };
    if (i == 'cameraId') {
      dialogFrom['cameraIds'] = row[i] && row[i].split(',') || [];
    };
    if (i == 'city') {
      dialogFrom[i] = row[i] && row[i].split(',') || [];
    };
  };
  nextTick(async () => {
    if (dialogFrom.type) {
      organizationSelect.value = await globalVue.getSelect('organizationSelect', { type: dialogFrom.type || '' });
    }
    if (dialogFrom.hospitalIds) {
      citySelect.value = await globalVue.getSelect('newCitySelect', { hospitalId: dialogFrom.hospitalIds || '' });
    }
  });
};

function onDelete(row) {
  ElMessageBox.confirm(
    'Delete Vehicle ？',
    'Delete',
    {
      confirmButtonText: 'Confirm',
      cancelButtonText: 'Cancel'
    }
  )
    .then(() => {
      instance.proxy.$http.delete('archiveData.deleteAmbulance', { data: { id: row.id + '' } }).then(res => {
        onSearch();
        ElMessage({
          type: 'success',
          message: 'Delete Vehicle successfully',
        });
      });
    })
    .catch(() => { })
}

function indexOfStr(str, checkStr) {
  return str?.indexOf(checkStr) > -1
}

async function clearType(type, val){
  if (type == 1) {
    dialogFrom.hospitalIds = ''
    dialogFrom.city = ''
    citySelect.value = []
    if (val) {
      organizationSelect.value = await globalVue.getSelect('organizationSelect', { type: dialogFrom.type || '' });
    }else{
      organizationSelect.value = []
    }
  }
  if (type == 2) {
    dialogFrom.city = ''
    citySelect.value = []
    if (val) {
      citySelect.value = await globalVue.getSelect('newCitySelect', { hospitalId: dialogFrom.hospitalIds || '' });
    }else{
      citySelect.value = []
    }
  }
}
</script>
<template>
  <div class="table_index">
    <SearchTable :selectClassification="selectClassification" :selectHospital="selectHospital" :selectModel="selectModel" :searchForm="searchForm" :citySelect="citySearchSelect" @onSearch="onSearch" @addVehicle="onAdd" />
    <div class="table_content">
      <mw-table v-loading="tablLoading" :data="tableData" :pagination="pagination" @paginationChange="paginationChange" @operate1="palyVideo" @operate2="onDetail" @operate3="onDelete"></mw-table>
    </div>
  </div>

  <div class="dialog_plug" v-if="plugFlow">
    <div class="car_popup">
      <div class="item_box">
        <div class="camare_box" v-if="videoUrl1">
          <FlvVideo v-if="videoData[0].status != 0" ref="hlsVideoBefore" :src="videoUrl1"></FlvVideo>
          <img v-else class="no_video" src="@/assets/image/index/ico_offline.png" alt="">
        </div>
        <div class="camare_box" v-if="videoUrl2">
          <FlvVideo v-if="videoData[1].status != 0" ref="hlsVideoAfter" :src="videoUrl2"></FlvVideo>
          <img v-else class="no_video" src="@/assets/image/index/ico_offline.png" alt="">
        </div>
        <div class="car_title">{{ videoData[0]?.codenumber || '--' }}｜{{ videoData[0]?.carnumber || '--' }}</div>
        <div class="car_info">
          <img src="@/assets/image/index/ico_yiyuanst.png" alt="">
          <span>：{{ videoData[0]?.lng || '--' }}，{{ videoData[0]?.lat || '--' }}</span>
        </div>
        <div class="car_info">
          <img src="@/assets/image/index/ico_yiyuans.png" alt="">
          <span>：{{ videoData[0]?.hospital || '--' }}</span>
        </div>
        <div class="car_value">Driver：{{ videoData[0]?.driver || '--' }}</div>
        <div class="car_value">Speed：{{ indexOfStr(videoData[0]?.status, '1') ? videoData[0]?.speed || '--' : 0 }} km/h</div>
        <div class="car_value">Vehicle status：{{ indexOfStr(videoData[0]?.status, '1') ? videoData[0]?.speed ? 'Driving' : 'Stopped' : '--' }}</div>

      </div>

    </div>
    <div class="float" @click="cliseVideo"></div>
  </div>


  <mw-dialog :show="dialogShow" :title="dialogState + dialogTitle" width="920px" @submit="dialogSubmit" @close="dialogClose">
    <el-form ref="dialogRef" class="dialog_form" :inline="true" :model="dialogFrom" label-width="160px" :rules="dialogRules">
      <el-form-item label="Code Number" prop="codenumber">
        <el-input v-model="dialogFrom.codenumber" class="value_input" placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="Car Number" prop="carnumber">
        <el-input v-model="dialogFrom.carnumber" class="value_input" placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="Vehicle Name" prop="name">
        <el-input v-model="dialogFrom.name" class="value_input" placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="Classification" prop="type">
        <el-select class="value_input" v-model="dialogFrom.type" placeholder="Please select" @change="(val) => clearType(1, val)" filterable clearable>
          <el-option v-for="item in selectClassification" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="Organization" prop="hospitalIds">
        <el-select class="value_input" v-model="dialogFrom.hospitalIds" @change="(val) => clearType(2, val)" placeholder="Please select" filterable clearable>
          <el-option v-for="item in organizationSelect" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="City" prop="city">
        <el-select class="value_input" v-model="dialogFrom.city" placeholder="Please select" multiple collapse-tags collapse-tags-tooltip filterable clearable>
          <el-option v-for="item in citySelect" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <div>
        <el-form-item label="AIBOX Camera" style="width: 88%">
          <el-select style="width: 100%;" v-model="dialogFrom.cameraIds" placeholder="Please select" multiple :multiple-limit="2" filterable clearable>
            <el-option v-for="item in selectCameraDialog" :key="item.id" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </div>
      <el-form-item label="Vehicle Model">
        <el-select class="value_input" v-model="dialogFrom.model" placeholder="Please select" filterable clearable>
          <el-option v-for="item in selectModel" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="Number Of Passengers">
        <el-select class="value_input" v-model="dialogFrom.passagernum" placeholder="Please select" filterable clearable>
          <el-option v-for="item in selectPassager" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="Maintenance Cycle">
        <el-select class="value_input" v-model="dialogFrom.maintaincycle" placeholder="Please select" filterable clearable>
          <el-option v-for="item in selectCycle" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="Rretirement Date">
        <el-date-picker v-model="dialogFrom.retirementperiod" value-format="YYYY-MM-DD" type="date" clearable />
      </el-form-item>
      <!-- <el-form-item label="Driver">
        <el-select class="value_input" v-model="dialogFrom.driverId" placeholder="Please select" filterable clearable>
          <el-option v-for="item in selectDriver" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item> -->
    </el-form>
  </mw-dialog>
</template>
<style scoped lang="less">
.dialog_plug {
  position: fixed;
  left: 0;
  top: 60px;
  width: 100%;
  height: calc(100% - 60px);
  z-index: 50;

  .car_popup {
    width: 420px;
    // height: 100%;
    padding: 10px;
    // backdrop-filter: blur(5px);
    background-color: #ffffff;
    position: absolute;
    right: 10px;
    border-radius: 8px;
    top: 10px;
    z-index: 100;
    display: flex;
    justify-content: space-between;
    box-shadow: 0px 0 12px 1px rgba(0, 0, 0, 0.16);

    .item_box {
      width: calc(100%);
      height: 100%;
      font-size: 14px;
      color: var(--mw-font-color-content);

      .car_value {
        margin: 10px 0;
      }

      .car_info {
        display: flex;
        align-items: center;
        margin: 10px 0;

        img {
          width: 22px;
          height: 22px;
        }
      }

      .car_title {
        height: 22px;
        color: var(--mw-font-color-title);
        font-size: 16px;
        margin: 8px 0;
      }

      .camare_box {
        width: 100%;
        height: 225px;
        border-radius: 2px;
        margin-bottom: 15px;
        overflow: hidden;
        background-color: #EDF0F4;

        img {
          width: 100%;
          height: 100%;
          margin: 0 auto;
          display: block;
        }

        video {
          width: 100%;
          height: 100%;
        }
      }
    }
  }

  .float {
    width: 100%;
    height: 100%;
    z-index: 50;
  }

}
</style>